package org.cboard.security.filters;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.cboard.dao.BoardDao;
import org.cboard.pojo.DashboardBoard;
import org.cboard.security.token.TokenUtils;
import org.cboard.security.utils.SpringContextHolder;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.Map;

/**
 * Created by zengxiangbin on 2017/1/13.
 */
public class PublicURLProcessingFilter implements Filter {


    private static BoardDao boardDao =SpringContextHolder.getBean("boardDao");


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getParameter("token");
        String errorMsg = null;

        Map<String,Object> map = Maps.newHashMap(httpServletRequest.getParameterMap());

        if (StringUtils.isNotEmpty(token)) {
            //经过测试有些浏览器不会自动decode
            if (token.contains("%")){
                token = URLDecoder.decode(token,"utf-8");
            }
            try {
                JSONObject tokenObj = TokenUtils.parseToken(token);
                Long boardId =   tokenObj.getLong(TokenUtils.boardIDKey);
//                Long userId = (Integer) tokenObj.get(TokenUtils.userIDKey) * 1L;
                DashboardBoard board = boardDao.getBoard(boardId);

                Integer ACTIVE_FLAG = 1;
                if (null != board && (board.getPublishStatus().equals(ACTIVE_FLAG))) {
                    String publishUrl = board.getPublishUrl();
                    String tempStr[] = publishUrl.split("token=");
					String systoken = URLDecoder.decode(tempStr[1],"utf-8");
                    //验证传入token是否和保存的token一致
                    if (token.equals(systoken)) {
                        //TODO 验证当前用户是否有此页面权限
                        map.put("token", token);
                        map.put("id", boardId);

                    } else {
                        errorMsg = "非法token，拒绝访问！";
                    }
                } else {
                    errorMsg = "此页面已关闭！";
                }
            } catch (Exception e) {

                e.printStackTrace();
                errorMsg = "非法token，拒绝访问！";

            }

        } else {
            errorMsg = "非法token，拒绝访问！";
        }

        if (null != errorMsg) {//验证不通过！
            HttpServletResponse response1 = (HttpServletResponse) response;
            response1.sendError(HttpServletResponse.SC_FORBIDDEN, errorMsg);
            JSONObject errorCode = new JSONObject();
            errorCode.put("status", HttpServletResponse.SC_FORBIDDEN);
            errorCode.put("msg", errorMsg);
            this.returnMsg(response1, errorCode);
            return;
        }

        ParameterRequestWrapper wrapRequest = new ParameterRequestWrapper(httpServletRequest, map);

        chain.doFilter(wrapRequest, response);

    }

    @Override
    public void destroy() {

    }

    public void returnMsg(HttpServletResponse response, JSONObject obj) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter out;
        try {
            out = response.getWriter();
            out.print(JSON.toJSONString(obj));
            out.println();
            out.flush();
            out.close();
        } catch (IOException ignored) {

        }
    }
}